package cn.yunyichina.provider.drug.service.impl;

import cn.yunyichina.provider.drug.dao.DeliveryDao;
import cn.yunyichina.provider.drug.dao.MatchedDao;
import cn.yunyichina.provider.drug.dao.MatchedOutDao;
import cn.yunyichina.provider.drug.entity.Delivery;
import cn.yunyichina.provider.drug.entity.Matched;
import cn.yunyichina.provider.drug.entity.MatchedOut;
import cn.yunyichina.provider.drug.vo.DeliveryDealVo;
import cn.yunyichina.provider.drug.vo.DeliveryVoRequest;
import cn.yunyichina.provider.framework.annotation.validate.ValidateException;
import cn.yunyichina.provider.framework.annotation.validate.Validator;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.dubbo.service.*;
import cn.yunyichina.provider.framework.exception.CallException;
import cn.yunyichina.provider.framework.page.PageInfo;
import cn.yunyichina.provider.iface.entity.ErrorCodeDefine;
import cn.yunyichina.provider.iface.entity.base.AddressBookVo;
import cn.yunyichina.provider.iface.entity.base.OrderExtVo;
import cn.yunyichina.provider.iface.entity.base.Org;
import cn.yunyichina.provider.iface.entity.base.Rule;
import cn.yunyichina.provider.iface.entity.cache.SessionInfo;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.provider.iface.entity.drug.DeliveryVo;
import cn.yunyichina.provider.iface.entity.message.AppMessageVo;
import cn.yunyichina.provider.iface.entity.message.TemplateCode;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import cn.yunyichina.utils.log.Log;
import cn.yunyichina.utils.log.constant.LogParamType;
import cn.yunyichina.utils.log.constant.LogScene;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2017/7/27.
 */
@Service
public class DeliveryServiceImpl {

    private Logger logger = LoggerFactory.getLogger(DeliveryServiceImpl.class);

    @Autowired
    private MatchedDao matchedDao;

    @Autowired
    private DeliveryDao deliveryDao;

    @Autowired
    private MatchedOutDao matchedOutDao;

    @Resource
    private Properties yaml;

    /**
     * 确认配送
     * yyt.drug.delivery.confirm
     * @param data
     * @param sessionId
     * @return
     * @throws Exception
     */
    public Response confirmDelivery(String data, String sessionId) throws Exception {
        logger.info("【drug模块-确认配送】确认配送--->method:confirmDelivery,data:" + data);
        Response response = new Response();
        DeliveryVoRequest requestVo = JsonUtils.parseObject(data,DeliveryVoRequest.class);

        // 校验RequestVo的数据
        try {
            Validator.getInstance().validate(requestVo);
        } catch (ValidateException ex) {
            logger.info("【drug模块-确认配送】数据校验失败:" + ex.getMessage() + "|入参:" + data + "！");
            logger.error("error", ex);
            response.setResultCodeAndMessage("23001", "数据校验失败:" + ex.getMessage() + "！");
            return response;
        }
        if(requestVo.getDeliveryMethod() != null){
            Integer method = Integer.valueOf(requestVo.getDeliveryMethod());
            if(!(method==1?true:method==2?true:false)){
                response.setResultCodeAndMessage("23001", "delivery_method值非法");
                logger.info("【drug模块-确认配送】结束, 返回结果=" + JsonUtils.toJsonString(response));
                return response;
            }
        }
        if(requestVo.getCourierFeePayMethod() != null){
            Integer method = Integer.valueOf(requestVo.getCourierFeePayMethod());
            if(!(method==1?true:method==2?true:false)){
                response.setResultCodeAndMessage("23001", "courier_fee_pay_method值非法");
                logger.info("【drug模块-确认配送】结束, 返回结果=" + JsonUtils.toJsonString(response));
                return response;
            }
        }

        //-----------------------------------------------------------------------------------------------------

        /**根据订单好查出订单对象**/
        Map<String, String> ordQueryMap = new HashMap<String, String>();
        ordQueryMap.put("order_no", requestVo.getOrderNo());
        Response ordResponse = BaseService.callUnderlineFromInternal(sessionId,
                "yyt.base.order.by.orderno.get", JsonUtils.toJsonString(ordQueryMap));
        if(!"0".equals(ordResponse.getResultCode())){
            logger.error("【drug模块-提交订单(本地匹配)】查询订单失败 " + requestVo.getOrderNo());
            response.setResultCodeAndMessage("9002", "查询订单失败。");
            return response;
        }
        OrderExtVo order = JsonUtils.parseObject(ordResponse.getResult(), OrderExtVo.class);
        /**根据订单好查出订单对象 end****************/
        if(order == null){
            logger.error("【drug模块-提交订单(本地匹配)】查询订单为空 订单号=" +requestVo.getOrderNo() + ",ordResponse="+ JSON.toJSONString(ordResponse));
            response.setResultCodeAndMessage("9002", "查询订单失败。");
            return response;
        }

        if(StringUtils.isBlank(requestVo.getDrugOrderNo())){
            logger.info("【drug模块-确认配送】开始走本地匹配下单");
            response = confirmDeliveryLocal(requestVo, order, sessionId);
        }else{
            logger.info("【drug模块-确认配送】开始走第三方的匹配下单");
            response = confirmDeliveryOutSide(requestVo, order, sessionId);
        }

        logger.info("【drug模块-确认配送】结束, 返回结果=" + JsonUtils.toJsonString(response));
        return response;
    }

    /**
     * 提交订单(本地匹配)
     * @param requestVo
     * @return
     */
    public Response confirmDeliveryLocal(DeliveryVoRequest requestVo, OrderExtVo order, String sessionId){
        Response response = new Response();

        try {
            Matched matchedQuery = new Matched();
            matchedQuery.setMatchedNo(requestVo.getMatchedNo());
            matchedQuery.setCompanyCode(requestVo.getCompanyCode());
            List<Matched> matchedList =  matchedDao.select(matchedQuery);
            if(CollectionUtils.isEmpty(matchedList)){
                logger.error("【drug模块-提交订单(本地匹配)-查询已匹配结果】本地查询不到matched_no[" + requestVo.getMatchedNo() + "],company_code[" + requestVo.getCompanyCode() + "]对应的匹配结果");
                response.setResultCodeAndMessage("23003", "本地查询不到matched_no[" + requestVo.getMatchedNo() + "],company_code[" + requestVo.getCompanyCode() + "]对应的匹配结果");
                return response;
            }
            Matched matched = matchedList.get(0);

            Org store = BaseService.getBaseClient().getOrgByCode(requestVo.getStoreCode());
            if (store == null) {
                logger.error("【drug模块-提交订单(本地匹配)-查询已匹配结果】没有store_code[" + requestVo.getStoreCode() + "]对应的机构信息");
                response.setResultCodeAndMessage("23004", "没有store_code[" + requestVo.getStoreCode() + "]对应的机构信息");
                return response;
            }

            Delivery delivery = new Delivery();
            delivery.setId(PKGenerator.generateId());
            delivery.setOrderNo(order.getOrderNo());
            delivery.setHospitalCode(order.getOrgCode());
            delivery.setHospitalName(order.getOrgName());
            delivery.setDeptCode(order.getDeptCode());
            delivery.setDeptName(order.getDeptName());
            delivery.setDoctorCode(order.getDoctorCode());
            delivery.setDoctorName(order.getDoctorName());
            delivery.setUserName(order.getUserName());
            delivery.setUserMobile(order.getUserMobile());
            delivery.setUserSex(order.getUserSex());
            delivery.setMedicalCardType(order.getMedicalCardType());
            delivery.setMedicalCardNo(order.getMedicalCardNo());
            delivery.setIdCardType(order.getIdCardType());
            delivery.setIdCardNo(order.getIdCardNo());
            delivery.setInsuranceCardNo(order.getInsuranceCardNo());

            if(StringUtils.isNotBlank(order.getExtraParams())){
                JSONObject extraParams = JSON.parseObject(order.getExtraParams());
                delivery.setReceiptId(extraParams.getString("recipe_id"));
                delivery.setMzFeeId(extraParams.getString("mz_fee_id"));
            }

            delivery.setCompanyCode(matched.getCompanyCode());
            delivery.setCompanyName(matched.getCompanyName());
            delivery.setMatchedNo(matched.getMatchedNo());

            delivery.setStoreCode(requestVo.getStoreCode());
            delivery.setStoreName(store.getOrgName());
            delivery.setStoreContactName(store.getContactName());
            delivery.setStoreContactTel(store.getContactTel());
            delivery.setStoreLatitude(store.getLatitude());
            delivery.setStoreLongitude(store.getLongitude());

            delivery.setDeliveryFeeDesc(requestVo.getDeliveryFeeDesc());
            delivery.setDeliveryMethod(requestVo.getDeliveryMethod());
            if(requestVo.getDeliveryMethod() != null && requestVo.getDeliveryMethod() == 1){
                delivery.setProvinceName(store.getProvinceName());
                delivery.setCityName(store.getCityName());
                delivery.setAreaName(store.getAreaName());
                delivery.setAddress(store.getAddress());
                delivery.setConsigneeName(order.getUserName());
                delivery.setConsigneeMobile(order.getUserMobile());

                Integer deliveryFee = 0;
                delivery.setDeliveryFee(deliveryFee);
                delivery.setMatchedFee(matched.getPayAmount());
                delivery.setPayAmount(delivery.getMatchedFee() + delivery.getDeliveryFee());

            }else if(requestVo.getDeliveryMethod() != null && requestVo.getDeliveryMethod() == 2){
                if(StringUtils.isBlank(requestVo.getCityName())){
                    logger.info("【drug模块-提交订单(本地匹配)】数据校验失败,入参city_name不能为空");
                    response.setResultCodeAndMessage("9001", " 数据校验失败,入参city_name不能为空");
                    return response;
                }else if(StringUtils.isBlank(requestVo.getAreaName())){
                    logger.info("【drug模块-提交订单(本地匹配)】数据校验失败,入参area_name不能为空");
                    response.setResultCodeAndMessage("9001", " 数据校验失败,入参area_name不能为空");
                    return response;
                }else if(StringUtils.isBlank(requestVo.getAddress())){
                    logger.info("【drug模块-提交订单(本地匹配)】数据校验失败,入参address不能为空");
                    response.setResultCodeAndMessage("9001", " 数据校验失败,入参address不能为空");
                    return response;
                }else if(StringUtils.isBlank(requestVo.getConsigneeName())){
                    logger.info("【drug模块-提交订单(本地匹配)】数据校验失败,入参consignee_name不能为空");
                    response.setResultCodeAndMessage("9001", " 数据校验失败,入参consignee_name不能为空");
                    return response;
                }else if(StringUtils.isBlank(requestVo.getConsigneeMobile())){
                    logger.info("【drug模块-提交订单(本地匹配)】数据校验失败,入参consignee_mobile不能为空");
                    response.setResultCodeAndMessage("9001", " 数据校验失败,入参consignee_mobile不能为空");
                    return response;
                }else if(requestVo.getCourierFeePayMethod() == null || requestVo.getCourierFeePayMethod().intValue() == 0){
                    logger.info("【drug模块-提交订单(本地匹配)】数据校验失败,入参courier_fee_pay_method不能为空");
                    response.setResultCodeAndMessage("9001", " 数据校验失败,入参courier_fee_pay_method不能为空");
                    return response;
                }else if(requestVo.getCourierFeePayMethod().intValue() != 1 && requestVo.getCourierFeePayMethod().intValue() != 2){
                    logger.info("【drug模块-提交订单(本地匹配)】数据校验失败,入参courier_fee_pay_method数据错误");
                    response.setResultCodeAndMessage("9001", " 数据校验失败,入参courier_fee_pay_method数据错误");
                    return response;
                }

                delivery.setCourierFeePayMethod(requestVo.getCourierFeePayMethod());

                if(StringUtils.isNotBlank(requestVo.getEstimatedDeliveryTime())){
                    delivery.setEstimatedDeliveryTime(requestVo.getEstimatedDeliveryTime());
                }

                delivery.setProvinceName(requestVo.getProvinceName());
                delivery.setCityName(requestVo.getCityName());
                delivery.setAreaName(requestVo.getAreaName());
                delivery.setAddress(requestVo.getAddress());
                delivery.setConsigneeName(requestVo.getConsigneeName());
                delivery.setConsigneeMobile(requestVo.getConsigneeMobile());

                /**根据条件查询配送费**/
                Map<String, String> deliveryFeeQueryMap = new HashMap<String, String>();
                deliveryFeeQueryMap.put("order_no", requestVo.getOrderNo());
                deliveryFeeQueryMap.put("company_code", requestVo.getCompanyCode());
                deliveryFeeQueryMap.put("store_code", requestVo.getStoreCode());
                deliveryFeeQueryMap.put("delivery_method", String.valueOf(requestVo.getDeliveryMethod()));
                deliveryFeeQueryMap.put("courier_fee_pay_method", String.valueOf(requestVo.getCourierFeePayMethod()));
                Response deliveryFeeQueryResponse = DrugService.callUnderlineFromInternal(sessionId,
                        "yyt.drug.delivery.pay.amount.get", JsonUtils.toJsonString(deliveryFeeQueryMap));
                logger.info("【drug模块-提交订单(本地匹配)】根据条件查询配送费, yyt.drug.delivery.pay.amount.get, deliveryFeeQueryResponse="+ JSON.toJSONString(deliveryFeeQueryResponse));
                if(!"0".equals(deliveryFeeQueryResponse.getResultCode())){
                    logger.error("【drug模块-提交订单(本地匹配)】根据条件查询配送费失败：" + deliveryFeeQueryResponse.getResultMessage());
                    response.setResultCodeAndMessage("23002", "根据条件查询配送费失败：" + deliveryFeeQueryResponse.getResultMessage());
                    return response;
                }
                Integer deliveryFee = JsonUtils.parseObject(deliveryFeeQueryResponse.getResult(), Integer.class);
                delivery.setDeliveryFee(deliveryFee);

                delivery.setMatchedFee(matched.getPayAmount());
                delivery.setPayAmount(delivery.getMatchedFee() + delivery.getDeliveryFee());

                if(StringUtils.isNotBlank(requestVo.getAddressBookId())){
                    AddressBookVo addressBookVo = new AddressBookVo();
                    addressBookVo.setId(requestVo.getAddressBookId());
                    addressBookVo.setUseTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                    BaseService.callUnderlineFromInternal(sessionId,"yyt.base.address.book.save", JsonUtils.toJsonString(addressBookVo));
                }
            }

            delivery.setOrderStatus(DeliveryVo.ORDER_STATUS_CREATE);
            delivery.setCreatedTime(DateUtils.dateToString(new Date()));
            Delivery query = new Delivery();
            query.setOrderNo(order.getOrderNo());
            List<Delivery> queryList = deliveryDao.select(query);
            if(CollectionUtils.isEmpty(queryList)) {
                deliveryDao.insert(delivery);
            }else{
                Delivery queryDelivery = queryList.get(0);
                if(queryDelivery.getOrderStatus() != DeliveryVo.ORDER_STATUS_CREATE){
                    //如果订单状态不是创建状态，则不允许重复下单
                    logger.info("【drug模块-提交订单(本地匹配)】订单状态不是创建状态，不允许重复下单");
                    response.setResultCodeAndMessage("23001", " 订单状态不是创建状态，不允许重复下单");
                    return response;
                }
                logger.info("【drug模块-提交订单(本地匹配)】库中已有订单的配送信息，不插入，执行更新，订单号："  + order.getOrderNo());
                delivery.setId("");
                updateDeliveryInner(delivery);
            }

            String oldOrgCode = order.getOrgCode();
            String oldOrgName = order.getOrgName();
            Integer oldPayAmount = order.getPayAmount();
            Integer oldTotalAmount = order.getTotalAmount();

            order.setOrgCode(matched.getCompanyCode());
            order.setOrgName(matched.getCompanyName());
            order.setPayAmount(delivery.getPayAmount());
            order.setTotalAmount(delivery.getPayAmount());
            if(StringUtils.isNotBlank(order.getExtraParams())){
                JSONObject extraParams = JSON.parseObject(order.getExtraParams());
                logger.info("delivery="  + JsonUtils.toJsonString(delivery));
                String drug_old_org_code = extraParams.get("drug_old_org_code")==null?"":extraParams.get("drug_old_org_code").toString();
                if(StringUtils.isBlank(drug_old_org_code)){
                    extraParams.put("drug_old_org_code",oldOrgCode);
                    extraParams.put("drug_old_org_name",oldOrgName);
                    extraParams.put("drug_old_pay_amount",oldPayAmount);
                    extraParams.put("drug_old_total_amount",oldTotalAmount);
                }
                extraParams.put("drug_store_code",delivery.getStoreCode());
                extraParams.put("drug_store_name",delivery.getStoreName());
                extraParams.put("drug_store_contactName",delivery.getStoreContactName());
                extraParams.put("drug_store_contactTel",delivery.getStoreContactTel());
                extraParams.put("drug_address",delivery.getAddress());
                extraParams.put("drug_province_name",delivery.getProvinceName());
                extraParams.put("drug_city_name",delivery.getCityName());
                extraParams.put("drug_area_name",delivery.getAreaName());
                extraParams.put("drug_store_latitude",delivery.getStoreLatitude());
                extraParams.put("drug_store_longitude",delivery.getStoreLongitude());
                extraParams.put("drug_consignee_name",delivery.getConsigneeName());
                extraParams.put("drug_consignee_mobile",delivery.getConsigneeMobile());
                extraParams.put("drug_delivery_method",delivery.getDeliveryMethod());
                extraParams.put("drug_courier_fee_pay_method",delivery.getCourierFeePayMethod());
                extraParams.put("drug_delivery_fee",delivery.getDeliveryFee());
                extraParams.put("drug_matched_fee",delivery.getMatchedFee());
                extraParams.put("drug_delivery_fee_desc",delivery.getDeliveryFeeDesc());
                extraParams.put("drug_estimated_delivery_time",delivery.getEstimatedDeliveryTime());
                order.setExtraParams(JsonUtils.toJsonString(extraParams));
            }
            BaseService.callUnderlineFromInternal(sessionId,"yyt.base.order.update", JsonUtils.toJsonString(order));

            response.setResultCodeAndMessage("0","成功");
        } catch (Exception e) {
            e.printStackTrace();
            response.setResultCodeAndMessage("23999", "系统异常:" + e.getMessage());
        }

        return response;
    }

    /**
     * 提交订单(第三方接口匹配)
     * @param requestVo
     * @return
     */
    public Response confirmDeliveryOutSide(DeliveryVoRequest requestVo, OrderExtVo order, String sessionId){
        Response response = new Response();

        try {
            if(requestVo.getDeliveryMethod() != null && requestVo.getDeliveryMethod() == 1){
                if(StringUtils.isBlank(requestVo.getDrugStoreCode())){
                    logger.info("【drug模块-提交订单(第三方匹配)】数据校验失败,入参drug_store_code不能为空");
                    response.setResultCodeAndMessage("9001", " 数据校验失败,入参drug_store_code不能为空");
                    return response;
                }
                if(StringUtils.isBlank(requestVo.getDrugStoreName())){
                    logger.info("【drug模块-提交订单(第三方匹配)】数据校验失败,入参drug_store_name不能为空");
                    response.setResultCodeAndMessage("9001", " 数据校验失败,入参drug_store_name不能为空");
                    return response;
                }
            }

            MatchedOut matchedOutQuery = new MatchedOut();
            matchedOutQuery.setOrderNo(requestVo.getOrderNo());
            matchedOutQuery.setCompanyCode(requestVo.getCompanyCode());
            matchedOutQuery.setDrugStoreId(requestVo.getDrugStoreCode());
            matchedOutQuery.setDrugOrderNo(requestVo.getDrugOrderNo());
            List<MatchedOut> matchedOutList =  matchedOutDao.select(matchedOutQuery);
            if(CollectionUtils.isEmpty(matchedOutList)){
                logger.error("【drug模块-提交订单(第三方匹配)-查询已匹配结果】查询不到order_no[" + requestVo.getOrderNo() + "],company_code[" + requestVo.getCompanyCode() + "],drug_order_no[" + requestVo.getDrugOrderNo() + "]对应的匹配结果");
                response.setResultCodeAndMessage("23003", "查询不到order_no[" + requestVo.getOrderNo() + "],company_code[" + requestVo.getCompanyCode() + "],drug_order_no[" + requestVo.getDrugOrderNo() + "]对应的匹配结果");
                return response;
            }
            MatchedOut matchedOut = matchedOutList.get(0);

            Org store = BaseService.getBaseClient().getOrgByCode(requestVo.getStoreCode());
            if (store == null) {
                logger.error("【drug模块-提交订单(第三方匹配)-查询门店机构】没有store_code[" + requestVo.getStoreCode() + "]对应的机构信息");
                response.setResultCodeAndMessage("23004", "没有store_code[" + requestVo.getStoreCode() + "]对应的机构信息");
                return response;
            }

            Delivery delivery = new Delivery();
            delivery.setId(PKGenerator.generateId());
            delivery.setOrderNo(order.getOrderNo());
            delivery.setHospitalCode(order.getOrgCode());
            delivery.setHospitalName(order.getOrgName());
            delivery.setDeptCode(order.getDeptCode());
            delivery.setDeptName(order.getDeptName());
            delivery.setDoctorCode(order.getDoctorCode());
            delivery.setDoctorName(order.getDoctorName());
            delivery.setUserName(order.getUserName());
            delivery.setUserMobile(order.getUserMobile());
            delivery.setUserSex(order.getUserSex());
            delivery.setMedicalCardType(order.getMedicalCardType());
            delivery.setMedicalCardNo(order.getMedicalCardNo());
            delivery.setIdCardType(order.getIdCardType());
            delivery.setIdCardNo(order.getIdCardNo());
            delivery.setInsuranceCardNo(order.getInsuranceCardNo());

            if(StringUtils.isNotBlank(order.getExtraParams())){
                JSONObject extraParams = JSON.parseObject(order.getExtraParams());
                delivery.setReceiptId(extraParams.getString("recipe_id"));
                delivery.setMzFeeId(extraParams.getString("mz_fee_id"));
            }

            delivery.setCompanyCode(matchedOut.getCompanyCode());
            delivery.setCompanyName(matchedOut.getCompanyName());
            delivery.setMatchedNo(matchedOut.getMatchedNo());

            delivery.setStoreCode(requestVo.getStoreCode());
            delivery.setStoreName(store.getOrgName());
            delivery.setStoreContactName(store.getContactName());
            delivery.setStoreContactTel(store.getContactTel());
            delivery.setStoreLatitude(store.getLatitude());
            delivery.setStoreLongitude(store.getLongitude());

            delivery.setDeliveryFeeDesc(requestVo.getDeliveryFeeDesc());
            delivery.setDeliveryMethod(requestVo.getDeliveryMethod());

            delivery.setDrugOrderNo(requestVo.getDrugOrderNo());
            delivery.setDrugStoreCode(requestVo.getDrugStoreCode());
            delivery.setDrugStoreName(requestVo.getDrugStoreName());

            if(requestVo.getDeliveryMethod() != null && requestVo.getDeliveryMethod() == 1){
                if(!requestVo.getDeliveryMethod().equals(matchedOut.getSupDeliveryMethod())){
                    logger.error("【drug模块-提交订单(第三方匹配)-检查匹配参数】下单参数delivery_method[" + requestVo.getDeliveryMethod() + "]和匹配参数delivery_method[" + matchedOut.getSupDeliveryMethod() + "]不符合");
                    response.setResultCodeAndMessage("23003", "下单参数delivery_method[" + requestVo.getDeliveryMethod() + "]和匹配参数delivery_method[" + matchedOut.getSupDeliveryMethod() + "]不符合");
                    return response;
                }

                delivery.setProvinceName(store.getProvinceName());
                delivery.setCityName(store.getCityName());
                delivery.setAreaName(store.getAreaName());
                delivery.setAddress(store.getAddress());
                delivery.setConsigneeName(order.getUserName());
                delivery.setConsigneeMobile(order.getUserMobile());

                delivery.setDeliveryFee(matchedOut.getDeliveryFee());
                delivery.setMatchedFee(matchedOut.getPayAmount());
                delivery.setPayAmount(matchedOut.getTotalAmount());

            }else if(requestVo.getDeliveryMethod() != null && requestVo.getDeliveryMethod() == 2){
                if(!requestVo.getDeliveryMethod().equals(matchedOut.getSupDeliveryMethod())){
                    logger.error("【drug模块-提交订单(第三方匹配)-检查匹配参数】下单参数delivery_method[" + requestVo.getDeliveryMethod() + "]和匹配参数delivery_method[" + matchedOut.getSupDeliveryMethod() + "]不符合");
                    response.setResultCodeAndMessage("23003", "下单参数delivery_method[" + requestVo.getDeliveryMethod() + "]和匹配参数delivery_method[" + matchedOut.getSupDeliveryMethod() + "]不符合");
                    return response;
                }

                if(StringUtils.isBlank(requestVo.getCityName())){
                    logger.info("【drug模块-提交订单(第三方匹配)】数据校验失败,入参city_name不能为空");
                    response.setResultCodeAndMessage("9001", " 数据校验失败,入参city_name不能为空");
                    return response;
                }else if(StringUtils.isBlank(requestVo.getAreaName())){
                    logger.info("【drug模块-提交订单(第三方匹配)】数据校验失败,入参area_name不能为空");
                    response.setResultCodeAndMessage("9001", " 数据校验失败,入参area_name不能为空");
                    return response;
                }else if(StringUtils.isBlank(requestVo.getAddress())){
                    logger.info("【drug模块-提交订单(第三方匹配)】数据校验失败,入参address不能为空");
                    response.setResultCodeAndMessage("9001", " 数据校验失败,入参address不能为空");
                    return response;
                }else if(StringUtils.isBlank(requestVo.getConsigneeName())){
                    logger.info("【drug模块-提交订单(第三方匹配)】数据校验失败,入参consignee_name不能为空");
                    response.setResultCodeAndMessage("9001", " 数据校验失败,入参consignee_name不能为空");
                    return response;
                }else if(StringUtils.isBlank(requestVo.getConsigneeMobile())){
                    logger.info("【drug模块-提交订单(第三方匹配)】数据校验失败,入参consignee_mobile不能为空");
                    response.setResultCodeAndMessage("9001", " 数据校验失败,入参consignee_mobile不能为空");
                    return response;
                }else if(requestVo.getCourierFeePayMethod() == null || requestVo.getCourierFeePayMethod().intValue() == 0){
                    logger.info("【drug模块-提交订单(第三方匹配)】数据校验失败,入参courier_fee_pay_method不能为空");
                    response.setResultCodeAndMessage("9001", " 数据校验失败,入参courier_fee_pay_method不能为空");
                    return response;
                }else if(requestVo.getCourierFeePayMethod().intValue() != 1 && requestVo.getCourierFeePayMethod().intValue() != 2){
                    logger.info("【drug模块-提交订单(第三方匹配)】数据校验失败,入参courier_fee_pay_method数据错误");
                    response.setResultCodeAndMessage("9001", " 数据校验失败,入参courier_fee_pay_method数据错误");
                    return response;
                }

                delivery.setCourierFeePayMethod(requestVo.getCourierFeePayMethod());

                if(StringUtils.isNotBlank(requestVo.getEstimatedDeliveryTime())){
                    delivery.setEstimatedDeliveryTime(requestVo.getEstimatedDeliveryTime());
                }

                delivery.setProvinceName(requestVo.getProvinceName());
                delivery.setCityName(requestVo.getCityName());
                delivery.setAreaName(requestVo.getAreaName());
                delivery.setAddress(requestVo.getAddress());
                delivery.setConsigneeName(requestVo.getConsigneeName());
                delivery.setConsigneeMobile(requestVo.getConsigneeMobile());
                delivery.setDeliveryFee(matchedOut.getDeliveryFee());
                delivery.setMatchedFee(matchedOut.getPayAmount());
                delivery.setPayAmount(matchedOut.getTotalAmount());

                if(StringUtils.isNotBlank(requestVo.getAddressBookId())){
                    AddressBookVo addressBookVo = new AddressBookVo();
                    addressBookVo.setId(requestVo.getAddressBookId());
                    addressBookVo.setUseTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                    BaseService.callUnderlineFromInternal(sessionId,"yyt.base.address.book.save", JsonUtils.toJsonString(addressBookVo));
                }
            }

            delivery.setOrderStatus(DeliveryVo.ORDER_STATUS_CREATE);
            delivery.setCreatedTime(DateUtils.dateToString(new Date()));
            Delivery query = new Delivery();
            query.setOrderNo(order.getOrderNo());
            List<Delivery> queryList = deliveryDao.select(query);
            if(CollectionUtils.isEmpty(queryList)) {
                deliveryDao.insert(delivery);
            }else{
                Delivery queryDelivery = queryList.get(0);
                if(queryDelivery.getOrderStatus() != DeliveryVo.ORDER_STATUS_CREATE){
                    logger.info("【drug模块-提交订单(第三方匹配)】订单状态不是创建状态，不允许重复下单");
                    response.setResultCodeAndMessage("23001", " 订单状态不是创建状态，不允许重复下单");
                    return response;
                }
                logger.info("【drug模块-提交订单(第三方匹配)】库中已有订单的配送信息，不插入，执行更新，订单号："  + order.getOrderNo());
                delivery.setId("");
                updateDeliveryInner(delivery);
            }

            String oldOrgCode = order.getOrgCode();
            String oldOrgName = order.getOrgName();
            Integer oldPayAmount = order.getPayAmount();
            Integer oldTotalAmount = order.getTotalAmount();

            order.setOrgCode(matchedOut.getCompanyCode());
            order.setOrgName(matchedOut.getCompanyName());
            order.setPayAmount(delivery.getPayAmount());
            order.setTotalAmount(delivery.getPayAmount());
            if(StringUtils.isNotBlank(order.getExtraParams())){
                JSONObject extraParams = JSON.parseObject(order.getExtraParams());
                logger.info("delivery="  + JsonUtils.toJsonString(delivery));
                String drug_old_org_code = extraParams.get("drug_old_org_code")==null?"":extraParams.get("drug_old_org_code").toString();
                if(StringUtils.isBlank(drug_old_org_code)){
                    extraParams.put("drug_old_org_code",oldOrgCode);
                    extraParams.put("drug_old_org_name",oldOrgName);
                    extraParams.put("drug_old_pay_amount",oldPayAmount);
                    extraParams.put("drug_old_total_amount",oldTotalAmount);
                }
                extraParams.put("drug_store_code",delivery.getStoreCode());
                extraParams.put("drug_store_name",delivery.getStoreName());
                extraParams.put("drug_store_contactName",delivery.getStoreContactName());
                extraParams.put("drug_store_contactTel",delivery.getStoreContactTel());
                extraParams.put("drug_address",delivery.getAddress());
                extraParams.put("drug_province_name",delivery.getProvinceName());
                extraParams.put("drug_city_name",delivery.getCityName());
                extraParams.put("drug_area_name",delivery.getAreaName());
                extraParams.put("drug_store_latitude",delivery.getStoreLatitude());
                extraParams.put("drug_store_longitude",delivery.getStoreLongitude());
                extraParams.put("drug_consignee_name",delivery.getConsigneeName());
                extraParams.put("drug_consignee_mobile",delivery.getConsigneeMobile());
                extraParams.put("drug_delivery_method",delivery.getDeliveryMethod());
                extraParams.put("drug_courier_fee_pay_method",delivery.getCourierFeePayMethod());
                extraParams.put("drug_delivery_fee",delivery.getDeliveryFee());
                extraParams.put("drug_matched_fee",delivery.getMatchedFee());
                extraParams.put("drug_delivery_fee_desc",delivery.getDeliveryFeeDesc());
                extraParams.put("drug_estimated_delivery_time",delivery.getEstimatedDeliveryTime());
                order.setExtraParams(JsonUtils.toJsonString(extraParams));
            }
            BaseService.callUnderlineFromInternal(sessionId,"yyt.base.order.update", JsonUtils.toJsonString(order));

            response.setResultCodeAndMessage("0","成功");
        } catch (Exception e) {
            e.printStackTrace();
            response.setResultCodeAndMessage("23999", "系统异常:" + e.getMessage());
        }

        return response;
    }

    /**
     * 根据条件查询订单
     * @param data
     * @interface yyt.drug.delivery.list
     * @return
     */
    public Response listDelivery(String data) {
        Response response = new Response();
        Map<String, Object> result = new HashMap<>();
        Delivery query = JsonUtils.parseObject(data, Delivery.class);
        Map<String, String> map = JsonUtils.parseObject(data, Map.class);
        String queryType = map.get("query_type");

        List<Delivery> deliveryList = null;

        if("auto".equals(queryType)){
            deliveryList  = deliveryDao.select(query);
            if(deliveryList != null && deliveryList.size() > 0){
                response.setResult(JsonUtils.toJsonString(result));
                response.setResultCodeAndMessageAndResult("0", "查询成功!",JsonUtils.toJsonString(deliveryList.get(0)));
            }else{
                response.setResultCodeAndMessage("0" , "查无结果");
                response.setResult("[]");
            }
        }
        else{
            if(StringUtils.isBlank(query.getHandleFlag())){
                query.setHandleFlag("0");
            }
            List<String> orderColumns = new ArrayList<String>();
            PageInfo pageInfo = null;
            if(query != null){
                orderColumns.add("CREATED_TIME");
                pageInfo = JsonUtils.parseObject(data, PageInfo.class);
                deliveryList  = deliveryDao.select(query, orderColumns , false ,pageInfo);
            }

            if(deliveryList != null && deliveryList.size() > 0){
                if(pageInfo != null && pageInfo.getPageNum() !=null && pageInfo.getPageSize() != null){
                    long totalSize = deliveryDao.selectCount(query);
                    pageInfo.setTotal(totalSize);
                    pageInfo.setPages((pageInfo.getTotal().intValue() + pageInfo.getPageSize() - 1) / pageInfo.getPageSize());
                    result.put("page_info", pageInfo);
                }
                result.put("list", deliveryList);
                response.setResult(JsonUtils.toJsonString(result));
                response.setResultCodeAndMessage("0", "查询成功!");
            }else{
                response.setResultCodeAndMessage("0" , "查无结果");
                response.setResult("[]");
            }
        }
        logger.info("【drug模块-根据条件查询订单】结束, 返回结果=" + JsonUtils.toJsonString(response));
        return response;

    }

    public Delivery selectByOrderNo(String orderNo){
        return deliveryDao.selectByOrderNo(orderNo);
    }

    /**
     * 更新配送订单数据
     * @param delivery
     */
    public Delivery updateDeliveryInner(Delivery delivery) {

        try {
            if (StringUtils.isBlank(delivery.getId())) {
                Delivery deliveryDb = deliveryDao.selectByOrderNo(delivery.getOrderNo());
                if (deliveryDb == null) {
                    throw new CallException(ErrorCodeDefine.ORDER_NO_INVALID,"没有指定订单号的订单记录");
                }
                delivery.setId(deliveryDb.getId());
                delivery.setHospitalCode(deliveryDb.getHospitalCode());
                delivery.setHospitalName(deliveryDb.getHospitalName());
            }
            delivery.setUpdateTime(DateUtils.dateToString(new Date()));
            logger.debug("要修改的updateOrder:"+JsonUtils.toJsonString(delivery));
            deliveryDao.update(delivery);

            return delivery;
        } catch (Exception e) {
            logger.error("修改订单错误"+e.toString());
            throw new CallException(ErrorCodeDefine.ORDER_COMMON, "修改订单错误",e);
        }
    }

    /**
     * 订单处理
     * @param data
     * @interface yyt.drug.delivery.deal
     * @return
     */
    public Response DealDelivery(String data, String sessionId) {
        Response response = new Response();
        DeliveryDealVo requestVo = JsonUtils.parseObject(data, DeliveryDealVo.class);

        // 校验RequestVo的数据
        try {
            Validator.getInstance().validate(requestVo);
        } catch (ValidateException ex) {
            logger.info(" 数据校验失败:" + ex.getMessage() + "|入参:" + data + "！");
            logger.error("error", ex);
            response.setResultCodeAndMessage("9001", "数据校验失败:" + ex.getMessage() + "！");
            return response;
        }

        Map<String, String> ordQueryMap = new HashMap<String, String>();
        ordQueryMap.put("order_no",requestVo.getOrderNo());
        Response ordResponse = BaseService.callUnderlineFromInternal("",
                "yyt.base.order.by.orderno.get", JsonUtils.toJsonString(ordQueryMap));
        if(!"0".equals(ordResponse.getResultCode())){
            logger.error("查询订单失败 " + requestVo.getOrderNo());
            response.setResultCodeAndMessage("9005","查无此订单");
            return response;
        }
        OrderExtVo order = JsonUtils.parseObject(ordResponse.getResult(), OrderExtVo.class);
        if(order == null){
            logger.error("查询订单为空 订单号=" + requestVo.getOrderNo() + ",ordResponse="+ JSON.toJSONString(ordResponse));
            response.setResultCodeAndMessage("9005","查无此订单");
            return response;
        }

        Delivery delivery = deliveryDao.selectByOrderNo(requestVo.getOrderNo());
        if(delivery == null){
            response.setResultCodeAndMessage("9005","查无此订单");
            return response;
        }

        if("1".equals(requestVo.getDealFlag())){
            if(!("2".equals(order.getOrderStatus().toString()) && "3".equals(order.getPayStatus().toString()) && "10".equals(order.getOrderType().toString()))){
                logger.error("【drug模块-订单处理接口】接单失败，当前订单不支持该操作, 订单类型=" + order.getOrderType() + ",订单状态=" + order.getOrderStatus() + ",支付状态=" + order.getPayStatus());
                response.setResultCodeAndMessage("23009", "接单失败，当前订单不支持该操作");
                return response;
            }

            order.setOrderStatus(OrderExtVo.ORDER_STATUS_SUCCESS);
            delivery.setOrderStatus(DeliveryVo.ORDER_STATUS_SUCCESS);
            sendMsg2user(order,2);
        }

        else if("2".equals(requestVo.getDealFlag())){
            if(!("2".equals(order.getOrderStatus().toString()) && "3".equals(order.getPayStatus().toString()) && "10".equals(order.getOrderType().toString()))){
                logger.error("【drug模块-订单处理接口】拒单失败，当前订单不支持该操作, 订单类型=" + order.getOrderType() + ",订单状态=" + order.getOrderStatus() + ",支付状态=" + order.getPayStatus());
                response.setResultCodeAndMessage("23009", "拒单失败，当前订单不支持该操作");
                return response;
            }

            try {
                //第三方原渠道退费
                Map<String, Object> jsonMap = new HashMap<String, Object>();
                jsonMap.put("hospital_code", order.getOrgCode());
                jsonMap.put("order_no", order.getOrderNo());
                if (1 == order.getIsInsurance()) {//没有医保的订单
                    Map<String, Object> extraParams = JsonUtils.parseObject(order.getExtraParams(), Map.class);
                    jsonMap.put("his_order_no", extraParams.get("cancel_bill_no"));
                    jsonMap.put("his_serial_no", extraParams.get("cancel_serial_no"));
                    jsonMap.put("refund_amount", order.getTotalAmount());
                } else {
                    jsonMap.put("his_order_no", order.getHisOrderNo());
                    jsonMap.put("refund_amount", order.getPayAmount());
                }
                jsonMap.put("refund_time", DateUtils.dateToString(new Date()));
                jsonMap.put("refund_reason", "拒单");
                jsonMap.put("refund_flag", 1);
                jsonMap.put("push_type", 0);
                Response refundResponse = PayService.callUnderlineFromInternal("", "yyt.pay.refund.channel.origin", JsonUtils.toJsonString(jsonMap));
                logger.info("【drug模块-订单处理接口】：退费返回" + JsonUtils.toJsonString(refundResponse) + ",订单号：" + order.getOrderNo());
                if ("0".equals(refundResponse.getResultCode())) {
                    order.setPayStatusRefunded();
                    order.setOrderStatus(OrderExtVo.ORDER_PAY_STATUS_REFUNDED);
                    delivery.setOrderStatus(OrderExtVo.ORDER_PAY_STATUS_REFUNDED);
                    response.setResultCodeAndMessage("0", "拒单退费成功");
                } else {
                    order.setPayStatusWaitRefund();//第三方退费失败，状态改成待退费
                    order.setOrderStatus(OrderExtVo.ORDER_PAY_STATUS_WAIT_REFUND);
                    delivery.setOrderStatus(OrderExtVo.ORDER_PAY_STATUS_WAIT_REFUND);
                    response.setResultCodeAndMessage(refundResponse.getResultCode(), refundResponse.getResultMessage());
                }
                delivery.setOperationResponse("订单拒单退费结果：" + JsonUtils.toJsonString(refundResponse));
            }catch (Exception e){
                logger.info("调用原渠道退费发送异常" + requestVo.getOrderNo() + ",异常：" + e.getMessage());
                order.setPayStatusWaitRefund();//第三方退费失败，状态改成待退费
                delivery.setOrderStatus(OrderExtVo.ORDER_PAY_STATUS_WAIT_REFUND);
                delivery.setOperationResponse("异常：" + e.getMessage());
                response.setResultCodeAndMessage("23999", "拒单退费异常：" + e.getMessage());
            }

            //发送拒单模板消息
            sendMsg2user(order,3);
        }

        else if("3".equals(requestVo.getDealFlag())){
            //只有用户申请了退费的订单（orderstatus＝2／3&paystatus＝5）或者 退费异常需要重新发起退费（orderstatus＝5&paystatus＝5）才允许后台审批退费
            if(!(("2".equals(order.getOrderStatus().toString()) || "3".equals(order.getOrderStatus().toString()) || "5".equals(order.getOrderStatus().toString())) && "5".equals(order.getPayStatus().toString()) && "10".equals(order.getOrderType().toString()))){
                logger.error("【drug模块-订单处理接口】后台同意退费失败，本订单类型错误, 订单类型=" + order.getOrderType() + ",订单状态=" + order.getOrderStatus() + ",支付状态=" + order.getPayStatus());
                response.setResultCodeAndMessage("23009", "同意退费失败，当前订单不支持该操作");
                return response;
            }

            //确认通过用户的退费申请
            try {
                //第三方原渠道退费
                Map<String, Object> jsonMap = new HashMap<String, Object>();
                jsonMap.put("hospital_code", order.getOrgCode());
                jsonMap.put("order_no", order.getOrderNo());
                if (1 == order.getIsInsurance()) {//没有医保的订单
                    Map<String, Object> extraParams = JsonUtils.parseObject(order.getExtraParams(), Map.class);
                    jsonMap.put("his_order_no", extraParams.get("cancel_bill_no"));
                    jsonMap.put("his_serial_no", extraParams.get("cancel_serial_no"));
                    jsonMap.put("refund_amount", order.getTotalAmount());
                } else {
                    jsonMap.put("his_order_no", order.getHisOrderNo());
                    jsonMap.put("refund_amount", order.getPayAmount());
                }
                jsonMap.put("refund_time", DateUtils.dateToString(new Date()));
                jsonMap.put("refund_reason", "审核取消");
                jsonMap.put("refund_flag", 1);
                jsonMap.put("push_type", 0);
                Response refundResponse = PayService.callUnderlineFromInternal("", "yyt.pay.refund.channel.origin", JsonUtils.toJsonString(jsonMap));
                logger.info("【drug模块-订单处理接口】：退费返回" + JsonUtils.toJsonString(refundResponse) + ",订单号：" + order.getOrderNo());
                if ("0".equals(refundResponse.getResultCode())) {
                    order.setPayStatusRefunded();
                    order.setOrderStatus(OrderExtVo.ORDER_PAY_STATUS_REFUNDED);
                    delivery.setOrderStatus(OrderExtVo.ORDER_PAY_STATUS_REFUNDED);
                    response.setResultCodeAndMessage("0", "审核退费成功");
                } else {
                    order.setPayStatusWaitRefund();//第三方退费失败，状态改成待退费
                    order.setOrderStatus(OrderExtVo.ORDER_PAY_STATUS_WAIT_REFUND);
                    delivery.setOrderStatus(OrderExtVo.ORDER_PAY_STATUS_WAIT_REFUND);
                    response.setResultCodeAndMessage(refundResponse.getResultCode(), refundResponse.getResultMessage());
                }
                delivery.setOperationResponse("订单审核退费结果：" + JsonUtils.toJsonString(refundResponse));
            }catch (Exception e){
                logger.info("调用原渠道退费发送异常" + requestVo.getOrderNo() + ",异常：" + e.getMessage());
                order.setPayStatusWaitRefund();//第三方退费失败，状态改成待退费
                delivery.setOrderStatus(OrderExtVo.ORDER_PAY_STATUS_WAIT_REFUND);
                delivery.setOperationResponse("异常：" + e.getMessage());
                response.setResultCodeAndMessage("23999", "审批退费异常：" + e.getMessage());
            }

        }

        else if("4".equals(requestVo.getDealFlag())){
            if(!(("2".equals(order.getOrderStatus().toString()) || "3".equals(order.getOrderStatus().toString())) && "3".equals(order.getPayStatus().toString()) && "10".equals(order.getOrderType().toString()))){
                logger.error("【drug模块-订单处理接口】申请退费失败，本订单类型错误, 订单类型=" + order.getOrderType() + ",订单状态=" + order.getOrderStatus() + ",支付状态=" + order.getPayStatus());
                response.setResultCodeAndMessage("23009", "申请退费失败，当前订单不支持该操作");
                return response;
            }

            String refundFlag = "2";//立即退费标志
            //未接单情况下
            if("2".equals(order.getOrderStatus().toString()) && "3".equals(order.getPayStatus().toString())){
                //获取未接单是否允许立即退费标志
                String drugRefundApplyUnprocess = "2";   //药店未接单是否允许立即退费 {"1":"允许","2":"禁止"}，默认返回2
                String ruleQuery = "{\"attribute_name\":\"drugRefundApplyUnprocess\",\"org_code\":\"" + delivery.getStoreCode() +"\"}";
                logger.info("【drug模块-订单处理接口】：获取未接单是否允许立即退费标志请求=" + ruleQuery);
                Response ruleResp = BaseService.callHumpFromInternal("yyt.base.rule.select",ruleQuery);
                logger.info("【drug模块-订单处理接口】：获取未接单是否允许立即退费标志返回=" + JsonUtils.toJsonString(ruleResp));
                if(ruleResp!=null && ruleResp.getResultCode().equals("0")){
                    Rule rule = JsonUtils.parseObject(ruleResp.getResult(),Rule.class);
                    if(rule != null){
                        drugRefundApplyUnprocess = rule.getAttributeProperties();
                    }
                }

                //允许立即退费
                if("1".equals(drugRefundApplyUnprocess)){
                    refundFlag = "1";
                }
            }

            if("1".equals(refundFlag)){
                logger.info("【drug模块-订单处理接口】：开始退费，refundFlag=" + refundFlag);
                try {
                    //第三方原渠道退费
                    Map<String, Object> jsonMap = new HashMap<String, Object>();
                    jsonMap.put("hospital_code", order.getOrgCode());
                    jsonMap.put("order_no", order.getOrderNo());
                    if (1 == order.getIsInsurance()) {//没有医保的订单
                        Map<String, Object> extraParams = JsonUtils.parseObject(order.getExtraParams(), Map.class);
                        jsonMap.put("his_order_no", extraParams.get("cancel_bill_no"));
                        jsonMap.put("his_serial_no", extraParams.get("cancel_serial_no"));
                        jsonMap.put("refund_amount", order.getTotalAmount());
                    } else {
                        jsonMap.put("his_order_no", order.getHisOrderNo());
                        jsonMap.put("refund_amount", order.getPayAmount());
                    }
                    jsonMap.put("refund_time", DateUtils.dateToString(new Date()));
                    jsonMap.put("refund_reason", "用户取消");
                    jsonMap.put("refund_flag", 1);
                    jsonMap.put("push_type", 0);
                    logger.info("【drug模块-订单处理接口】：退费请求=" + JsonUtils.toJsonString(jsonMap) + ",订单号：" + order.getOrderNo());
                    Response refundResponse = PayService.callUnderlineFromInternal("", "yyt.pay.refund.channel.origin", JsonUtils.toJsonString(jsonMap));
                    logger.info("【drug模块-订单处理接口】：退费返回=" + JsonUtils.toJsonString(refundResponse) + ",订单号：" + order.getOrderNo());
                    if ("0".equals(refundResponse.getResultCode())) {
                        order.setPayStatusRefunded();
                        order.setOrderStatus(OrderExtVo.ORDER_PAY_STATUS_REFUNDED);
                        delivery.setOrderStatus(OrderExtVo.ORDER_PAY_STATUS_REFUNDED);
                        logger.info("【drug模块-订单处理接口】：立即退费成功, refund_flag=1");
                        response.setResultCodeAndMessageAndResult("0", "申请退费成功","{\"refund_flag\":\"1\"}");
                    } else {
                        order.setPayStatusWaitRefund();//第三方退费失败，状态改成待退费
                        order.setOrderStatus(OrderExtVo.ORDER_PAY_STATUS_WAIT_REFUND);
                        delivery.setOrderStatus(OrderExtVo.ORDER_PAY_STATUS_WAIT_REFUND);
                        logger.info("【drug模块-订单处理接口】：立即退费失败, refund_flag=1");
                        response.setResultCodeAndMessageAndResult(refundResponse.getResultCode(), refundResponse.getResultMessage(),"{\"refund_flag\":\"1\"}");
                    }
                    delivery.setOperationResponse("订单用户申请退费退费结果：" + JsonUtils.toJsonString(refundResponse));
                }catch (Exception e){
                    logger.info("调用原渠道退费发送异常" + requestVo.getOrderNo() + ",异常：" + e.getMessage());
                    order.setPayStatusWaitRefund();//第三方退费失败，状态改成待退费
                    delivery.setOrderStatus(OrderExtVo.ORDER_PAY_STATUS_WAIT_REFUND);
                    delivery.setOperationResponse("异常：" + e.getMessage());
                    logger.info("【drug模块-订单处理接口】：立即退费异常, refund_flag=1");
                    response.setResultCodeAndMessageAndResult("23999", "用户申请退费异常：" + e.getMessage(),"{\"refund_flag\":\"1\"}");
                }
            }else{
                order.setPayStatusWaitRefund();
                logger.info("【drug模块-订单处理接口】：不退费，提交申请到后台处理，refundFlag=" + refundFlag);
                response.setResultCodeAndMessageAndResult("0", "申请退费提交成功，等待审核","{\"refund_flag\":\"2\"}");
            }

        }

        else if("5".equals(requestVo.getDealFlag())){
            if(!(("2".equals(order.getOrderStatus().toString()) || "3".equals(order.getOrderStatus().toString())) && "5".equals(order.getPayStatus().toString()) && "10".equals(order.getOrderType().toString()))){
                logger.error("【drug模块-订单处理接口】拒绝退费失败，本订单类型错误, 订单类型=" + order.getOrderType() + ",订单状态=" + order.getOrderStatus() + ",支付状态=" + order.getPayStatus());
                response.setResultCodeAndMessage("23009", "拒绝退费失败，当前订单不支持该操作");
                return response;
            }

            order.setPayStatusPayed();
            logger.info("【drug模块-订单处理接口】拒绝退费成功");
            response.setResultCodeAndMessage("0", "拒绝退费成功");
        }

        else{
            response.setResultCodeAndMessage("9005","无效的dealFlag");
            return response;
        }

        delivery.setOperationType(Short.parseShort(requestVo.getDealFlag()));
        SessionInfo sessionInfo = CacheService.getSessionInfo(sessionId);
        if(StringUtils.isNotBlank(requestVo.getOperators())){
            delivery.setOperators(requestVo.getOperators());
        }else{
            if(sessionInfo != null){
                delivery.setOperators(sessionInfo.getLoginName());
            }
        }
        if(StringUtils.isNotBlank(requestVo.getOpinions())){
            delivery.setOpinions(requestVo.getOpinions());
        }
        delivery.setUpdateTime(DateUtils.dateToString(new Date()));

        deliveryDao.update(delivery);
        BaseService.callUnderlineFromInternal("","yyt.base.order.update", JsonUtils.toJsonString(order));

        if("4".equals(requestVo.getDealFlag())){
            if(StringUtils.isNotBlank(delivery.getDrugOrderNo())){
                /**调用接口推送订单信息**/
                Map<String, String> pushMap = new HashMap<String, String>();
                pushMap.put("order_no", order.getOrderNo());
                pushMap.put("check_status", "1");
                Response pushResponse = DrugService.callUnderlineFromInternal(sessionId,
                        "yyt.drug.order.item.out.push", JsonUtils.toJsonString(pushMap));
                logger.info("【drug模块-订单处理接口】订单推送, yyt.drug.order.item.out.push, pushResponse="+ JSON.toJSONString(pushResponse));
                if(!"0".equals(pushResponse.getResultCode())){
                    logger.error("【drug模块-订单处理接口】订单推送失败：" + pushResponse.getResultMessage());
                    response.setResultCodeAndMessage("23002", "订单推送失败：" + pushResponse.getResultMessage());
                }else{
                    logger.info("【drug模块-订单处理接口】订单推送成功");
                }
                delivery.setOperationResponse("订单推送结果：" + JsonUtils.toJsonString(pushResponse));
            }
        }

        logger.info("【drug模块-订单处理接口】结束, 返回结果=" + JsonUtils.toJsonString(response));
        return response;

    }

    /** 未处理订单数量
     * yyt.drug.delivery.wait.deal.get
     * @param data
     * @param sessionId
     * @return
     */
    public Response getDeliveryWaitDeal(String data,String sessionId) {
        Response response = new Response();
        Delivery vo = JsonUtils.parseObject(data, Delivery.class);

        if(StringUtils.isBlank(vo.getCompanyCode()) && StringUtils.isBlank(vo.getStoreCode())){
            response.setResultCodeAndMessage("23001", "company_code和store_code不能同时为空");
            return response;
        }
        if(StringUtils.isNotBlank(vo.getCompanyCode()) && StringUtils.isNotBlank(vo.getStoreCode())){
            response.setResultCodeAndMessage("23001", "company_code和store_code只能指定其中一个");
            return response;
        }

        Delivery query = new Delivery();
        query.setOrderStatus(DeliveryVo.ORDER_STATUS_PAYED);
        if(StringUtils.isNotBlank(vo.getCompanyCode())){
            query.setCompanyCode(vo.getCompanyCode());
        }else{
            query.setStoreCode(vo.getStoreCode());
        }
        long count = deliveryDao.selectCount(query);
        response.setResultCodeAndMessage("0","查询成功");
        response.setResult("{\"count\":" + count +"}");
        return response;
    }

    /**
     * 发送新订单短信通知
     * @param delivery
     */
    public void sendNewOrderSms(Delivery delivery) throws Exception{
        logger.info("【drug模块-发送新订单短信通知】开始, delivery=" + JsonUtils.toJsonString(delivery));

        try {
            String ruleQuery = "{\"attribute_name\":\"newOrderNotifyType\",\"org_code\":\"" + delivery.getStoreCode() +"\"}";
            Response ruleResp = BaseService.callHumpFromInternal("yyt.base.rule.select",ruleQuery);
            String newOrderNotifyType="";
            if(ruleResp!=null && ruleResp.getResultCode().equals("0")){
                Rule rule = JsonUtils.parseObject(ruleResp.getResult(),Rule.class);
                newOrderNotifyType = rule.getAttributeProperties();
            }

            logger.info("【drug模块-发送新订单短信通知】newOrderNotifyType=" + newOrderNotifyType);

            if(newOrderNotifyType.indexOf("2") <0){
                //规则不用发送短信
                return ;
            }

            logger.info("【drug模块-发送新订单短信通知】开始发送短信......");

            Org org = BaseService.getBaseClient().getOrgByCode(delivery.getStoreCode());
            if (org == null) {
                logger.error("9000", "没有store_code对应的机构信息:" + delivery.getStoreCode() + "！");
                return ;
            }
            String mobile = org.getContactTel();
            if(StringUtils.isBlank(mobile)){
                return ;
            }
            String[]  tels = mobile.split(",");
            for(int i = 0;i<tels.length;i++){
                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("user_type", "5");
                dataMap.put("to_user", tels[i]);
                dataMap.put("msg_type", 23900);

                JSONObject content = new JSONObject();
                if(StringUtils.isNotBlank(delivery.getStoreName())){
                    content.put("store_name", delivery.getStoreName());
                }else{
                    content.put("store_name", delivery.getCompanyName());
                }

                dataMap.put("msg_content", content);
                String dataJson = JSON.toJSONString(dataMap);
                // 发送短信给医生
                logger.info("发送短信给药店，参数: " + dataJson);
                MessageService.callUnderlineFromInternal("yyt.message.msg.sms.send", dataJson);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     *
     * @param order
     * @param type 1:支付成功消息 2：接单 3：拒单消息
     */
    public void sendMsg2user(OrderExtVo order,int type){
        logger.info("【drug模块-发送支付成功消息】开始, order=" + JsonUtils.toJsonString(order) + ",type=" + type);
        // 消息推送
        try {
            short platformType = 2;
            if ("1".equals(String.valueOf(Integer.valueOf(order.getPayMode())/10%10))) {
                platformType = 1;
            }else if("2".equals(String.valueOf(Integer.valueOf(order.getPayMode())/10%10))){
                platformType = 2;
            }

            String url=yaml.getProperty("order.clinic.url")+"order_no="+order.getOrderNo()+"&app_code="+order.getPlatformOrgAppCode()+"&open_id="+order.getOpenId()+"&app_id="+order.getPayAppId();

            //消息重构
            AppMessageVo appMessageVo = new AppMessageVo();
            appMessageVo.setOpenId(order.getOpenId());
            appMessageVo.setPlatformOrgAppCode(order.getPlatformOrgAppCode());
            appMessageVo.setDevOrgCode(order.getPlatformCode());
            appMessageVo.setLibraryTemplateType((short) 3);
            appMessageVo.setPlatformType(platformType);
            appMessageVo.setUrl(url);
            Map<String,String> map = new HashedMap();
            switch (type){
                case 1://支付成功消息
                    appMessageVo.setPlatformTemplateCode(TemplateCode.PBM_PAY_SUCCESS.getCode());
                    map.put("orderNo",order.getOrderNo());
                    map.put("details","门特处方");
                    map.put("amount",order.getPayAmount()/100d + "元");
                    break;
                case 2://接单
                    appMessageVo.setPlatformTemplateCode(TemplateCode.PBM_GET_ORDER.getCode());
                    map.put("name",order.getOrgName());//药店名称
                    map.put("orderNo",order.getOrderNo());
                    break;
                case 3://拒单
                    appMessageVo.setPlatformTemplateCode(TemplateCode.PBM_REFUSE_ORDER.getCode());
                    map.put("orderNo",order.getOrderNo());
                    map.put("orderType","门特处方外购");
                    map.put("amount",order.getPayAmount()/100d + "元");
                    map.put("time",order.getPayTime().length() > 20?order.getPayTime().substring(0,19):order.getPayTime());
                    map.put("cause","药店没有接单。");
                    break;

            }
            appMessageVo.setMsgContentMap(map);

            Log.i(LogScene.PBM, "DeliveryServiceImpl.sendMsg2user", LogParamType.REQUEST, order.getOrderNo(),
                    "PBM外购单系统消息推送接口,入参request=" + JsonUtils.toJsonString(appMessageVo));
            ResponseObject messageResponse = MessageService.getMessageClient().sendAppMessage(appMessageVo);
            Log.i(LogScene.PBM, "DeliveryServiceImpl.sendMsg2user", LogParamType.RESPONSE, order.getOrderNo(),
                    "PBM外购单系统消息推送接口,调用message模块, 返回response=" + JsonUtils.toJsonString(messageResponse));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("处方外购, 支付成功后消息推送失败:", e);
        }
    }

    /**
     * 更新配送单
     * @param data
     * @interface yyt.drug.delivery.update
     * @return
     */
    public Response updateDelivery(String data) {
        logger.info("【drug模块-更新配送单】开始, 请求="+data);
        Response response = new Response();

        Delivery deliveryRequest = JsonUtils.parseObject(data, Delivery.class);

        if(deliveryRequest == null || StringUtils.isBlank(deliveryRequest.getOrderNo())){
            response.setResultCodeAndMessage("23001", "order_no不能为空");
            return response;
        }else{
            Delivery delivery = deliveryDao.selectByOrderNo(deliveryRequest.getOrderNo());
            if(delivery == null){
                response.setResultCodeAndMessage("23001", "无此订单信息");
                return response;
            }else{
                deliveryRequest.setId(delivery.getId());
                deliveryRequest.setUpdateTime(DateUtils.dateToString(new Date()));

                if(StringUtils.isNotBlank(deliveryRequest.getCourierNo())){
                    if(!deliveryRequest.getCourierNo().equals(delivery.getCourierNo())){
                        /**根据订单好查出订单对象**/
                        Map<String, String> ordQueryMap = new HashMap<String, String>();
                        ordQueryMap.put("order_no", deliveryRequest.getOrderNo());
                        Response ordResponse = BaseService.callUnderlineFromInternal("yyt.base.order.by.orderno.get", JsonUtils.toJsonString(ordQueryMap));
                        if(!"0".equals(ordResponse.getResultCode())){
                            logger.error("查询订单失败 " + deliveryRequest.getOrderNo());
                            response.setResultCodeAndMessage("23002", "查询订单失败。");
                            return response;
                        }
                        OrderExtVo order = JsonUtils.parseObject(ordResponse.getResult(), OrderExtVo.class);
                        /**根据订单好查出订单对象 end****************/
                        if(order == null){
                            logger.error("查询订单为空 订单号=" +deliveryRequest.getOrderNo() + ",ordResponse="+ JSON.toJSONString(ordResponse));
                            response.setResultCodeAndMessage("23002", "查询订单失败。");
                            return response;
                        }

                        if(StringUtils.isNotBlank(order.getExtraParams())){
                            JSONObject extraParams = JSON.parseObject(order.getExtraParams());
                            logger.info("extraParams="  + JsonUtils.toJsonString(extraParams));
                            extraParams.put("drug_courier_no",deliveryRequest.getCourierNo());//快递单号
                            order.setExtraParams(JsonUtils.toJsonString(extraParams));
                        }
                        BaseService.callUnderlineFromInternal("yyt.base.order.update", JsonUtils.toJsonString(order));
                    }
                }

                deliveryDao.update(deliveryRequest);
                response.setResultCodeAndMessage("0", "更新成功");
            }
        }
        logger.info("【drug模块-更新配送单】结束, 返回结果=" + JsonUtils.toJsonString(response));
        return response;
    }

    /**
     * 获取配送单所需配送费
     * @param data
     * @interface yyt.drug.delivery.pay.amount.get
     * @return
     */
    public Response getDeliveryPayAmount(String data, String sessionId) {
        logger.info("【drug模块-获取配送单所需配送费】开始, 请求=" + data + ",sessionId=" + sessionId);
        Response response = new Response();

        Integer deliveryFee = 0;

        Map<String,String> map = JsonUtils.parseObject(data,Map.class);
        String orderNo = map.get("order_no");
        String companyCode = map.get("company_code");
        String storeCode = map.get("store_code");
        String deliveryMethod = map.get("delivery_method");
        String courierFeePayMethod = map.get("courier_fee_pay_method");

        //检查入参
        if(StringUtils.isBlank(orderNo)){
            response.setResultCodeAndMessage("23001", "order_no不能为空");
            logger.info("【drug模块-获取配送单所需配送费】结束, 返回结果=" + JsonUtils.toJsonString(response));
            return response;
        }
        if(StringUtils.isBlank(companyCode)){
            response.setResultCodeAndMessage("23001", "company_code不能为空");
            logger.info("【drug模块-获取配送单所需配送费】结束, 返回结果=" + JsonUtils.toJsonString(response));
            return response;
        }
        if(StringUtils.isBlank(storeCode)){
            response.setResultCodeAndMessage("23001", "store_code不能为空");
            logger.info("【drug模块-获取配送单所需配送费】结束, 返回结果=" + JsonUtils.toJsonString(response));
            return response;
        }
        if(StringUtils.isBlank(deliveryMethod)){
            response.setResultCodeAndMessage("23001", "delivery_method不能为空");
            logger.info("【drug模块-获取配送单所需配送费】结束, 返回结果=" + JsonUtils.toJsonString(response));
            return response;
        }
        if(StringUtils.isBlank(courierFeePayMethod)){
            response.setResultCodeAndMessage("23001", "courier_fee_pay_method不能为空");
            logger.info("【drug模块-获取配送单所需配送费】结束, 返回结果=" + JsonUtils.toJsonString(response));
            return response;
        }

        Matched matchedQuery = new Matched();
        matchedQuery.setOrderNo(orderNo);
        matchedQuery.setCompanyCode(companyCode);
        List<Matched> matchedList =  matchedDao.select(matchedQuery);
        if(CollectionUtils.isEmpty(matchedList)){
            response.setResultCodeAndMessage("23003", "查询不到该药店的匹配结果");
            logger.info("【drug模块-获取配送单所需配送费】结束, 返回结果=" + JsonUtils.toJsonString(response));
            return response;
        }
        Matched matched = matchedList.get(0);
        Integer payAmount = matched.getPayAmount();

        if("1".equals(deliveryMethod)){
            deliveryFee = 0;
            response.setResultCodeAndMessageAndResult("0", "查询成功", JsonUtils.toJsonString(deliveryFee));
            logger.info("【drug模块-获取配送单所需配送费】结束, 【自提】返回结果=" + JsonUtils.toJsonString(response));
            return response;
        }else if("2".equals(deliveryMethod)){
            if("1".equals(courierFeePayMethod)){
                deliveryFee = getDeliveryFee(storeCode, payAmount);
                if(deliveryFee.intValue() == -1){
                    response.setResultCodeAndMessage("23999", "异常，获取配送单支付金额失败");
                    logger.info("【drug模块-获取配送单所需配送费】结束, 【配送】【在线支付】返回结果=" + JsonUtils.toJsonString(response));
                    return response;
                }else{
                    response.setResultCodeAndMessageAndResult("0", "查询成功", JsonUtils.toJsonString(deliveryFee));
                    logger.info("【drug模块-获取配送单所需配送费】结束, 【配送】【在线支付】返回结果=" + JsonUtils.toJsonString(response));
                    return response;
                }

            }else if("2".equals(courierFeePayMethod)){
                deliveryFee = 0;
                response.setResultCodeAndMessageAndResult("0", "查询成功", JsonUtils.toJsonString(deliveryFee));
                logger.info("【drug模块-获取配送单所需配送费】结束, 【配送】【邮费到付】返回结果=" + JsonUtils.toJsonString(response));
                return response;
            }else{
                response.setResultCodeAndMessage("23001", "无此快递费支付方式");
                logger.info("【drug模块-获取配送单所需配送费】结束, 返回结果=" + JsonUtils.toJsonString(response));
                return response;
            }
        }else{
            response.setResultCodeAndMessage("23001", "无此配送方式");
            logger.info("【drug模块-获取配送单所需配送费】结束, 返回结果=" + JsonUtils.toJsonString(response));
            return response;
        }
    }

    /**
     * 获取配送费
     * @param storeCode
     * @param payAmount
     * @return
     */
    private Integer getDeliveryFee(String storeCode, Integer payAmount){
        logger.info("【drug模块-获取配送费】开始, storeCode=" + storeCode + ",payAmount=" + payAmount);

        Integer deliveryFee = -1;
        Integer drugFreeCourierFee,drugCourierFee;

        try {
            String ruleQuery = "{\"attribute_name\":\"drugFreeCourierFee\",\"org_code\":\"" + storeCode +"\"}";
            Response ruleResp = BaseService.callHumpFromInternal("yyt.base.rule.select",ruleQuery);
            if(ruleResp!=null && ruleResp.getResultCode().equals("0")){
                Rule rule = JsonUtils.parseObject(ruleResp.getResult(),Rule.class);
                drugFreeCourierFee = Integer.parseInt(rule.getAttributeProperties());
            }else{
                logger.info("【drug模块-获取配送费】机构" + storeCode + "未配置drugFreeCourierFee规则");
                return deliveryFee;
            }

            ruleQuery = "{\"attribute_name\":\"drugCourierFee\",\"org_code\":\"" + storeCode +"\"}";
            ruleResp = BaseService.callHumpFromInternal("yyt.base.rule.select",ruleQuery);
            if(ruleResp!=null && ruleResp.getResultCode().equals("0")){
                Rule rule = JsonUtils.parseObject(ruleResp.getResult(),Rule.class);
                drugCourierFee = Integer.parseInt(rule.getAttributeProperties());
            }else{
                logger.info("【drug模块-获取配送费】机构" + storeCode + "未配置drugCourierFee规则");
                return deliveryFee;
            }

            if(payAmount.intValue() >= drugFreeCourierFee.intValue()){
                deliveryFee = 0;
            }else{
                deliveryFee = drugCourierFee;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("【drug模块-获取配送费】异常, error=" + e.getMessage());
        }

        logger.info("【drug模块-获取配送费】结束, 返回结果=" + JsonUtils.toJsonString(deliveryFee));
        return deliveryFee;
    }

}
